function Promise(fn) {
  this.cbs = [];

  const resolve = value => {
    setTimeout(() => {
      this.data = value;
      this.cbs.forEach(cb => {
        cb(value);
      });
    });
  };

  fn(resolve);
}

Promise.prototype.then = function(fulfilled) {
  return new Promise(resolve => {
    this.cbs.push(() => {
      const res = fulfilled(this.data);

      if (res instanceof Promise) {
        return res.then(resolve);
      } else {
        return resolve(res);
      }
    });
  });
};

const p1 = new Promise(resolve => {
  resolve(1);
});

p1.then(res => {
  console.log(res);
});
